<template>
  <div class="stock-in-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>入库单管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreateStockIn" v-permission="'inventory.stockIn.create'">
              <el-icon><Plus /></el-icon>
              新建入库单
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><RefreshRight /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
          <el-form-item label="入库单号">
            <el-input v-model="searchForm.orderNumber" placeholder="请输入入库单号" clearable @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item label="入库类型">
            <el-select v-model="searchForm.orderType" placeholder="选择入库类型" clearable>
              <el-option v-for="(name, value) in orderTypes" :key="value" :label="name" :value="Number(value)" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="searchForm.supplierId" placeholder="选择供应商" clearable filterable>
              <el-option v-for="supplier in suppliers" :key="supplier.id" :label="supplier.name" :value="supplier.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select v-model="searchForm.warehouseId" placeholder="选择仓库" clearable>
              <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option v-for="(name, value) in orderStatus" :key="value" :label="name" :value="Number(value)" />
            </el-select>
          </el-form-item>
          <el-form-item label="入库日期">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Delete /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 入库单列表 -->
      <el-table
        :data="stockInList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNumber" label="入库单号" min-width="150" show-overflow-tooltip />
        <el-table-column label="入库类型" width="120">
          <template #default="scope">
            {{ orderTypes[scope.row.orderType] || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="供应商" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.supplier ? scope.row.supplier.name : '无' }}
          </template>
        </el-table-column>
        <el-table-column label="仓库" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.warehouse ? scope.row.warehouse.name : '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="scope">
            <span>{{ formatPrice(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ orderStatus[scope.row.status] || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderDate" label="入库日期" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.orderDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="operator.name" label="操作人" width="120" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleViewStockIn(scope.row)"
              v-permission="'inventory.stockIn.view'"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleEditStockIn(scope.row)"
              v-permission="'inventory.stockIn.edit'"
              v-if="scope.row.status === 0"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="handleConfirmStockIn(scope.row)"
              v-permission="'inventory.stockIn.confirm'"
              v-if="scope.row.status === 0"
            >
              确认
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleCancelStockIn(scope.row)"
              v-permission="'inventory.stockIn.cancel'"
              v-if="scope.row.status === 0"
            >
              作废
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteStockIn(scope.row)"
              v-permission="'inventory.stockIn.delete'"
              v-if="scope.row.status === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getStockInOrders, 
  deleteStockInOrder, 
  confirmStockInOrder, 
  cancelStockInOrder,
  getAllWarehouses,
  getAllSuppliers
} from '@/api/inventory';
import { formatDateTime, formatPrice } from '@/utils/format';
import permission from '@/directives/permission';

export default {
  name: 'StockInList',
  directives: { permission },
  setup() {
    const router = useRouter();
    
    // 状态定义
    const loading = ref(false);
    const stockInList = ref([]);
    const total = ref(0);
    const page = ref(1);
    const pageSize = ref(20);
    const warehouses = ref([]);
    const suppliers = ref([]);
    
    // 入库单类型映射
    const orderTypes = {
      1: '采购入库',
      2: '退货入库',
      3: '调拨入库',
      4: '其他入库'
    };
    
    // 入库单状态映射
    const orderStatus = {
      0: '草稿',
      1: '已确认',
      2: '已取消'
    };
    
    // 搜索表单
    const searchForm = reactive({
      orderNumber: '',
      orderType: null,
      supplierId: null,
      warehouseId: null,
      status: null,
      dateRange: []
    });
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          return [start, end];
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          return [start, end];
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          return [start, end];
        }
      }
    ];
    
    // 获取入库单列表
    const fetchStockInOrders = async () => {
      loading.value = true;
      try {
        const params = {
          page: page.value,
          pageSize: pageSize.value,
          orderNumber: searchForm.orderNumber || undefined,
          orderType: searchForm.orderType || undefined,
          supplierId: searchForm.supplierId || undefined,
          warehouseId: searchForm.warehouseId || undefined,
          status: searchForm.status !== null ? searchForm.status : undefined,
          startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : undefined,
          endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : undefined
        };
        
        const response = await getStockInOrders(params);
        stockInList.value = response.data.items;
        total.value = response.data.total;
      } catch (error) {
        console.error('Failed to fetch stock-in orders:', error);
        ElMessage.error('获取入库单列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 加载仓库和供应商数据
    const loadMasterData = async () => {
      try {
        const [warehouseRes, supplierRes] = await Promise.all([
          getAllWarehouses(),
          getAllSuppliers()
        ]);
        warehouses.value = warehouseRes.data;
        suppliers.value = supplierRes.data;
      } catch (error) {
        console.error('Failed to load master data:', error);
        ElMessage.error('加载基础数据失败');
      }
    };
    
    // 根据状态获取标签类型
    const getStatusType = (status) => {
      const map = {
        0: 'info',    // 草稿
        1: 'success', // 已确认
        2: 'danger'   // 已取消
      };
      return map[status] || '';
    };
    
    // 分页操作
    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchStockInOrders();
    };
    
    const handleCurrentChange = (val) => {
      page.value = val;
      fetchStockInOrders();
    };
    
    // 搜索操作
    const handleSearch = () => {
      page.value = 1;
      fetchStockInOrders();
    };
    
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = key === 'dateRange' ? [] : null;
      });
      handleSearch();
    };
    
    // 刷新数据
    const refreshData = () => {
      fetchStockInOrders();
    };
    
    // 跳转到创建入库单页面
    const handleCreateStockIn = () => {
      router.push('/admin/inventory/stock-in/create');
    };
    
    // 查看入库单详情
    const handleViewStockIn = (row) => {
      router.push(`/admin/inventory/stock-in/view/${row.id}`);
    };
    
    // 编辑入库单
    const handleEditStockIn = (row) => {
      router.push(`/admin/inventory/stock-in/edit/${row.id}`);
    };
    
    // 确认入库单
    const handleConfirmStockIn = (row) => {
      ElMessageBox.confirm('确认该入库单将更新商品库存，是否继续？', '确认入库', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await confirmStockInOrder(row.id);
          ElMessage.success('入库单已确认');
          refreshData();
        } catch (error) {
          console.error('Failed to confirm stock-in order:', error);
          ElMessage.error('确认入库单失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    // 取消入库单
    const handleCancelStockIn = (row) => {
      ElMessageBox.confirm('取消入库单后将无法恢复，是否继续？', '取消入库', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await cancelStockInOrder(row.id);
          ElMessage.success('入库单已取消');
          refreshData();
        } catch (error) {
          console.error('Failed to cancel stock-in order:', error);
          ElMessage.error('取消入库单失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    // 删除入库单
    const handleDeleteStockIn = (row) => {
      ElMessageBox.confirm('删除入库单后将无法恢复，是否继续？', '删除入库单', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(async () => {
        try {
          await deleteStockInOrder(row.id);
          ElMessage.success('入库单已删除');
          refreshData();
        } catch (error) {
          console.error('Failed to delete stock-in order:', error);
          ElMessage.error('删除入库单失败');
        }
      }).catch(() => {
        // 用户取消操作
      });
    };
    
    onMounted(() => {
      fetchStockInOrders();
      loadMasterData();
    });
    
    return {
      loading,
      stockInList,
      total,
      page,
      pageSize,
      warehouses,
      suppliers,
      orderTypes,
      orderStatus,
      searchForm,
      dateShortcuts,
      handleSizeChange,
      handleCurrentChange,
      handleSearch,
      resetSearch,
      refreshData,
      handleCreateStockIn,
      handleViewStockIn,
      handleEditStockIn,
      handleConfirmStockIn,
      handleCancelStockIn,
      handleDeleteStockIn,
      getStatusType,
      formatDateTime,
      formatPrice
    };
  }
};
</script>

<style scoped>
.stock-in-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 